package com.myblog.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.myblog.mapper.LabelMapper;
import com.myblog.entity.Label;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
@CacheConfig(cacheNames = "BLOG:SESSION_KEY_IN_LABEL")
public class LabelServiceImpl implements LabelService {
    @Autowired
    private LabelMapper labelMapper;

    @Cacheable(key = "'LIST_P'+ #page +'L'+ #limit")
    @Override
    public List<Label> list() {
        return labelMapper.list();
    }

    @Cacheable(key = "'LID' +#id")
    @Override
    public Label listById(Integer id) {
        return labelMapper.listByLid(id);
    }

    @CacheEvict(allEntries = true) //此注解会清除cacheNames所有缓存
    @Override
    public void save(Label label) {
        if (label.getId() != null) {
            labelMapper.updateById(label);
        } else {
            labelMapper.save(label);
        }
    }

    @CacheEvict(allEntries = true) //此注解会清除cacheNames所有缓存
    @Override
    public void del(Integer lid) {
        //删除中间表
        labelMapper.delMiddle(lid);
        labelMapper.deleteById(lid);
    }

    @Cacheable(key = "#label.name",unless="#result == null")
    @Override
    public Label findByName(Label label) {
        return labelMapper.selectOne(new QueryWrapper<Label>().eq("name", label.getName()));
    }

    @Cacheable(key = "'total'", unless = "#result == null")
    @Override
    public Integer total() {
        return labelMapper.total();
    }
}
